﻿using System;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using EasyNetQ;
using K2.Listener.Entity;
using TableDependency.Enums;
using TableDependency.EventArgs;
using TableDependency.SqlClient;

namespace K2.Listener.Service
{
    public class ActInstSlotListener
    {
        public void Start()
        {
            var conn = Config.ConnectionStr;
            using (SqlConnection connection = new SqlConnection(conn))
            {
                var tableDependency = new SqlTableDependency<ActInstSlotEntity>(conn, "ServerLog.ActInstSlot");
                tableDependency.OnChanged += TableDependency_Changed;
                tableDependency.Start();
            }
        }

        private static void TableDependency_Changed(object sender, RecordChangedEventArgs<ActInstSlotEntity> e)
        {
            Console.WriteLine("Notice change!");
            if (e.ChangeType != ChangeType.None)
            {
                Console.WriteLine(e.ChangeType.ToString());
                var listenerEntity = new ActInstSlotListenerEntity
                {
                    ProcInstID = e.Entity.ProcInstID,
                    ActInstID=e.Entity.ActInstID,
                    User = e.Entity.User
                };
                JavaScriptSerializer js = new JavaScriptSerializer();
                var tm = js.Serialize(listenerEntity);
                Console.WriteLine(tm);
                SendMQMsg(listenerEntity);
            }
        }

        /// <summary>
        /// 发送同步任务至RabbitMQ
        /// </summary>
        /// <param name="msg"></param>
        private static void SendMQMsg(ActInstSlotListenerEntity msg)
        {
            var bus = RabbitHutch.CreateBus("host=192.168.184.149;username=aryan;password=demopc");
            bus.Send("k2.sync.task", msg);
            bus.Dispose();
        }
    }
}
